from channels.generic.websocket import WebsocketConsumer
from channels.exceptions import StopConsumer
from asgiref.sync import async_to_sync
import json


class RollCallConsumer(WebsocketConsumer):
    def websocket_connect(self, message):
        # 接收这个客户端的连接
        self.accept()
        # 将这个客户端的连接对象加入到某个地方（内存 or redis）1314 是群号这里写死了
        async_to_sync(self.channel_layer.group_add)('1314', self.channel_name)

    def websocket_receive(self, message):
        # 浏览器基于websocket向后端发送数据，自动触发接收消息
        # data = json.loads(message['text'])
        # chat_type = data.get('chat_type')
        # chat_id = data.get('chat_id')
        # chat_content = data.get('message')
        # print('chat_type', chat_type)
        # if chat_type == 'add_chat':
        #     async_to_sync(self.channel_layer.group_add)(chat_id, self.channel_name)

        # 通知组内的所有客户端，执行 chat_message 方法，在此方法中自己可以去定义任意的功能。

        async_to_sync(self.channel_layer.group_send)('1314', {"type": 'chat.message', 'message': message})

    # 这个方法对应上面的type，意为向1314组中的所有对象发送信息
    # 回调的方法
    def chat_message(self, event):
        text = event['message']['text']
        self.send(text)

    def websocket_disconnect(self, message):
        data = json.loads(message['text', '{}'])
        chat_id = data.get('chat_id')
        # 断开链接要将这个对象从 channel_layer 中移除
        async_to_sync(self.channel_layer.group_discard)(chat_id, self.channel_name)
        raise StopConsumer()
# consumer.py
# -*- coding: utf-8 -*-


import json

from channels.generic.websocket import AsyncJsonWebsocketConsumer
from channels.layers import get_channel_layer
from asgiref.sync import async_to_sync


# class RollCallConsumer(AsyncJsonWebsocketConsumer):
#     group_name = "face_safe"
#
#     async def connect(self):
#         await self.channel_layer.group_add(
#             self.group_name,
#             self.channel_name
#         )
#         await self.accept()
#
#     async def disconnect(self, close_code):
#         await self.channel_layer.group_discard(
#             self.group_name,
#             self.channel_name
#         )
#
#     async def receive(self, text_data=None, bytes_data=None, **kwargs):
#         await self.send(text_data)
#
#     async def send(self, text_data=None, bytes_data=None, close=False):
#         await super(RollCallConsumer, self).send(text_data, bytes_data, close)
#
#     async def push_messages(self, message):
#         message_type = message['message_type']
#         message = message['message']
#         data = {
#             'message_type': message_type,
#             'message': message
#         }
#         await self.send(json.dumps(data, ensure_ascii=False))
#
#
# def send_message(group_name="face_safe", message=None, message_type=None):
#     """
#     WS广播: 外部函数调用
#     :param message_type: 消息类型
#     :param group_name: 组名称
#     :param message: 消息内容
#     :return:
#     """
#     # print(get_channel_layer())
#     # print("send msg")
#     channel_layer = get_channel_layer()
#     async_to_sync(channel_layer.group_send)(
#         group_name,
#         {
#             'type': 'push.messages',  # push_messages函数
#             'message': message,
#             'message_type': message_type
#         }
#     )
